package com.qzimp.fujiancuo.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.mybatisflex.core.query.QueryWrapper;
import com.qzimp.fujiancuo.entity.*;
import com.qzimp.fujiancuo.entity.dto.CuoDto;
import com.qzimp.fujiancuo.entity.vo.ResultVo;
import com.qzimp.fujiancuo.mapper.CuoMapper;
import com.qzimp.fujiancuo.mapper.UserinfoLogMapper;
import com.qzimp.fujiancuo.mapper.UserinfoMapper;
import com.qzimp.fujiancuo.service.HuanghansenService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
public class HuanghansenController {

    @Resource
    CuoMapper cuoMapper;
    @Resource
    UserinfoMapper userinfoMapper;
    @Resource
    UserinfoLogMapper userinfoLogMapper;
    @Resource
    HuanghansenService huanghansenService;
    @Resource
    private JavaMailSender mailSender;

    @Resource
    HttpSession session;
    @Value("${spring.mail.username}")
    private String sender;
    @Value("${spring.mail.nickname}")
    private String nickname;



    @GetMapping("/getEventbyName")
    @ApiOperation(value = "根据厝Name获取事件", notes = "根据厝Name获取事件")
    public ResultVo getEventbyName(String name) {
        List<CuoDto> eventbyName = cuoMapper.getEventbyId(name);

        return new ResultVo(eventbyName);
    }

    @GetMapping("/getUserinfoAndLog")
    @ApiOperation(value = "根据用户id获取用户信息和操作信息", notes = "根据id获取用户信息和操作信息")
    public ResultVo getUserinfoAndLog(String id) {
        Userinfo userinfo = userinfoMapper.selectOneById(id);

        List<UserinfoLog> userinfoLogs = userinfoLogMapper.selectListByQuery(new QueryWrapper().eq("userinfo_id", id));
        UserinfoDto userinfoDto = new UserinfoDto();
        BeanUtils.copyProperties(userinfo, userinfoDto);
        userinfoDto.setUserinfoLogs(userinfoLogs);

        return new ResultVo(userinfoDto);
    }

    @GetMapping("/sendSimpleMail")
    @ApiOperation(value = "发送普通邮箱验证码", notes = "发送普通邮箱验证码")
    public ResultVo sendSimpleMail(String id) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(nickname + '<' + sender + '>');

        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(130, 48, 4, 10);

        String captchaText = circleCaptcha.getCode();
        String captchaImageBase64Data = circleCaptcha.getImageBase64Data();
        String captchaId = UUID.randomUUID().toString();

//        stringRedisTemplate.opsForValue().set("captcha:" + captchaId, captchaText, 30, TimeUnit.SECONDS);

        message.setTo("2426304544@qq.com");
        message.setSubject("闽南厝的验证码");
        String code = "123456";
        String content = "【验证码】您的验证码为：" + captchaText + " 。 验证码五分钟内有效，逾期作废。\n\n\n" +
                "------------------------------\n\n\n";

        System.out.println(captchaText);
        System.out.println(captchaImageBase64Data);
        System.out.println(captchaId);

        message.setText(content);
        mailSender.send(message);

        HashMap<String, Object> mp = new HashMap<>();
        mp.put("captchaId",captchaId);
        mp.put("captchaText",captchaText);
        session.setAttribute("id",captchaText);


        return new ResultVo(mp);
    }

    @GetMapping("/vert")
    @ApiOperation(value = "验证邮箱验证码", notes = "验证邮箱验证码")
    public String vert(String id,String vl) {

        String captchaId = (String)session.getAttribute("id");

        if (vl.equals(captchaId)){
            return "验证成功";
        }

        return "验证失败";
    }


    @GetMapping("/sendEmailWithImage")
    @ApiOperation(value = "发送图片邮箱验证码", notes = "发送图片邮箱验证码")
    public ResultVo sendEmailWithImage(String id) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(nickname + '<' + sender + '>');
        helper.setTo("2426304544@qq.com");
        helper.setSubject("闽南厝的验证码");

        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(130, 48, 4, 10);
        String captchaText = circleCaptcha.getCode();
        String captchaImageBase64Data = circleCaptcha.getImageBase64Data();
        String captchaId = UUID.randomUUID().toString();

        String htmlContent = "<html><body>" +
                "【验证码】您的验证码为：<img style='vertical-align: middle;' src='" + captchaImageBase64Data + "'/>。 验证码五分钟内有效，逾期作废。" +
                "</body></html>";

        System.out.println(captchaText);
        System.out.println(captchaImageBase64Data);
        System.out.println(captchaId);



        helper.setText(htmlContent, true);

        HashMap<String, Object> mp = new HashMap<>();
        mp.put("captchaId",captchaId);
        mp.put("captchaText",captchaText);
        mp.put("captchaImageBase64Data",captchaImageBase64Data);
        session.setAttribute("id",captchaText);



        mailSender.send(message);
//        return new ResultVo(CaptchaVO.builder().captchaId(captchaId).build());
        return new ResultVo(mp);
    }

    @PostMapping(value = "/uploadFile")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    ResultVo uploadFile(@RequestParam("md5") String md5, @RequestParam("fileName") String fileName, @RequestPart("file") MultipartFile file) {
        String filePath = null;

        try {
            File tempFile = File.createTempFile("chunk", ".temp");
            file.transferTo(tempFile);
            filePath = tempFile.getAbsolutePath();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        MinioFile minioFile = huanghansenService.uploadFile(md5, fileName, filePath);

        return new ResultVo(minioFile);
    }




}
